
#include <stdio.h>
#include "led.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_log.h"


static const char *TAG = "Led";

static TaskHandle_t ledBlinkTaskHandle = NULL;

typedef struct
{
    gpio_num_t led;
    uint16_t blink_period;    //闪烁周期
    uint8_t blink_times;     //闪烁的次数，255为一直闪
}LedCtrl;
LedCtrl ledCtrl;

// 初始化 LED 灯
void led_init()
{
    gpio_reset_pin(LED_Y);
    gpio_set_direction(LED_Y, GPIO_MODE_OUTPUT);

    gpio_reset_pin(LED_W);
    gpio_set_direction(LED_W, GPIO_MODE_OUTPUT);
}

// 控制 LED 灯的开和关
void led_control(gpio_num_t led, bool on)
{
    gpio_set_level(led, on ? 1 : 0);
}

void led_toggle(gpio_num_t led)
{
    static int level = 1;
    gpio_set_level(led, level);
    level = !level;
}

void led_task_function(void *pvParameter)
{
    LedCtrl ledCtrl = *(LedCtrl *)pvParameter;
    uint16_t times = ledCtrl.blink_times * 2;
    while (1)
    {
        if(times)
        {
            led_toggle(ledCtrl.led);
            vTaskDelay(ledCtrl.blink_period / portTICK_PERIOD_MS);
            if(ledCtrl.blink_times != 255)
                times--;
        }
        else
        {
            ESP_LOGI(TAG, "Stop blink : %d", ledCtrl.led);
            vTaskDelete(NULL);
        }
    }
}

void led_start_blink(gpio_num_t led, uint16_t period_ms, uint8_t times)
{
    ledCtrl.led = led;
    ledCtrl.blink_period = period_ms;
    ledCtrl.blink_times = times;
    xTaskCreate(&led_task_function, "Led_Blink_Task", 2048, (void *)&ledCtrl, 5, &ledBlinkTaskHandle);
    ESP_LOGI(TAG, "Start blink : %d", led);
}

void led_stop_blink(gpio_num_t led)
{
    vTaskDelete(ledBlinkTaskHandle);
    led_control(led, false);
    ESP_LOGI(TAG, "Stop blink : %d", led);
}